<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    // 闭包的各种骚操作
    // 1. 使用闭包实现once
    function once(func) {
        let flag = false;
        return function () {
            if (!flag) {
                func();
            }
            flag = true;
        }
    }
    let btnClick = once(()=>{
        alert('clicked');
    });

    // 闭包给内部函数传值
    function calcTime(func) {
        let prev = Date.now()
        return function() {
            let context = this;
            let args = arguments;
            console.log(func.apply(context,args));
            let cur = Date.now();
            console.log(cur-prev + 'ms');
            prev = cur;
        }
    }
    // 普通递归
    function factorial(n) {
        if(n==1) return 1;
        return n * factorial(n-1);
    }
    // 尾递归优化
    function factorial2(n, total) {
        if(n==1) return total;
        return factorial2(n-1, n*total)
    }
    let test1 = calcTime(factorial);
    let test2 = calcTime(factorial2);
    test1(20);
    test2(20,1);
    test2(20,1);
</script>
</body>
</html>
